package soulkun.library.utils.time

import android.text.format.DateFormat
import soulkun.library.utils.getAppContext
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

object TimeUtils {

    const val DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"
    const val DATE_FORMAT = "yyyy-MM-dd"
    const val EXACT_FORMAT = "yyyy-MM-dd HH:mm:ss SSS"
    const val FILE_FORMAT = "yyyy-MM-dd(HH-mm-ss)"
    const val TIME_FORMAT = "HH:mm:ss"

    /**
     * Date转时间戳字符串
     */
    fun dateToStringWithFormat(date: Date, pattern: String): String? {
        val dateFormat = SimpleDateFormat(pattern, Locale.CHINA)
        return dateFormat.format(date)
    }

    /**
     * 时间戳字符串转Date
     */
    fun stringToDateWithFormat(string: String, pattern: String): Date?{
        val simpleDateFormat = SimpleDateFormat(pattern, Locale.CHINA)
        return simpleDateFormat.parse(string)
    }

    /**
     * ms转成mm:ss格式
     */
    fun msToTime(ms: Int): String {
        val formatter = SimpleDateFormat("mm:ss")
        return formatter.format(ms)
    }

    /**
     * second转成hh:mm:ss格式，超过24小时自动转为24小时余数
     */
    fun secondToTime(seconds: Int): String{
        val daySeconds = 24 * 60 * 60
        val milliSeconds = seconds % daySeconds * 1000L
        return String.format(
            "%02d:%02d:%02d",
            TimeUnit.MILLISECONDS.toHours(milliSeconds),
            TimeUnit.MILLISECONDS.toMinutes(milliSeconds) -
                    TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliSeconds)),
            TimeUnit.MILLISECONDS.toSeconds(milliSeconds) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds))
        )
    }

    /**
     * 将时间戳字符串转成 HH:mm:ss格式
     */
    fun stringToTime(string: String, pattern: String): String? {
        val date = stringToDateWithFormat(string, pattern) ?: return null
        return dateToStringWithFormat(date, TIME_FORMAT)
    }

    /**
     * true day 白天   return false晚上
     * @return
     */
    fun isDayOrNight(): Boolean {
        if (get24HourMode()) {
            //24小时制
            val calendar = Calendar.getInstance()
            val curHour = calendar[Calendar.HOUR_OF_DAY]
            if (curHour in 6..18) {
                return true
            }
        } else {
            //12小时制
            val calendar = Calendar.getInstance()
            val curHour = calendar[Calendar.HOUR]
            if (calendar[Calendar.AM_PM] == 0) {
                //上午
                if (curHour in 6..12) {
                    return true
                }
            } else {
                //下午
                if (curHour in 0..6) {
                    return true
                }
            }
        }
        return false
    }

    //返回true是24小时制，否则是12小时制
    fun get24HourMode(): Boolean {
        return DateFormat.is24HourFormat(getAppContext())
    }


}
